/*********************************************************************************
 *      Copyright:  (C) 2022 xiezongyi<1764417007@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  mosquitto_client.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/05/22)
 *         Author:  xiezongyi <1764417007@qq.com>
 *      ChangeLog:  1, Release initial version on "04/05/22 09:01:02"
 *                 
 ********************************************************************************/

#include <time.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <getopt.h>
#include <libgen.h>
#include <signal.h>
#include <pthread.h>

#include "logger.h"
#include "database.h"
#include "mosquitto.h"
#include "cJSON_worker.h"
#include "thread_init.h"
#include "thread_worker.h"
#include "mosquitto_conf.h"
#include "mosquitto_callback_sub.h"
#include "temperature.h"

int					g_stop = 0;

void print_usage(char *program);
void signal_handler(int signum);

int main (int argc, char **argv)
{
	int					rv  = -1;
	int					ch = 0;
	int					daemon_run = 0;
	int					limit_time = 0;
	char				*platform;
	char				*db_name = "DS18B20_temper.db";
	mqtt_ctx_t			mqtt;
	pthread_t			tid;
	pthread_attr_t		thread_attr;

	struct option 		opts[] = {
		{"daemon", no_argument, NULL, 'd'},
		{"limit_time", required_argument, NULL, 't'},
		{"platform", required_argument, NULL, 'P'},
		{"help", no_argument, NULL, 'h'},
		{NULL, 0, NULL, 0}
	};

	char			*progname = basename(argv[0]);

	while((ch = getopt_long(argc, argv, "dt:P:h", opts, NULL)) != -1)
	{
		switch(ch)
		{
			case 'd':
				daemon_run = 1;
				break;
			case 't':
				mqtt.limit_time = atoi(optarg);
				break;
			case 'P':
				platform = optarg;
				strncpy(mqtt.platform, platform, sizeof(mqtt.platform));
				break;
			case 'h':
				print_usage(progname);
				return 0;

			default:
				break;
		}
	}

	//参数合法性检测
	if(!mqtt.platform || !mqtt.limit_time)
	{
		print_usage(progname);
		return 0;
	}

	signal(SIGTERM, signal_handler);

	//后台运行
	if(daemon_run)
	{
		daemon(1, 0);
	}

	//解析配置文件ini
	rv = get_mqtt_conf(&mqtt);
	if(rv < 0)
	{
		printf("get_mqtt_conf failure: %s\n", strerror(errno));
		if(-3 == rv)
		{
			printf("Choice platform or spell it error, the process will end!\n");
			exit(0);
		}
	}
	
	//初始化mosquitto库
	rv = mosquitto_lib_init();
	if(MOSQ_ERR_SUCCESS != rv)
	{
		printf("mosquitto_lib_init() faliure: %s\n", strerror(errno));
		goto cleanup;
	}
	printf("mosquitto_lib_init() OK!\n");

    //打开数据库并建表
    rv = database_init(&(mqtt.db), db_name);
    if(rv < 0)
    {
        printf("database_init() failure: %s\n", strerror(errno));
		goto cleanup;
    }
    printf("Open database and create table OK!\n");	

	//线程初始化
	if( thread_init(&thread_attr) < 0 )
	{
		printf("pthread_init() failure: %s\n", strerror(errno));
		goto cleanup;
	}

	//创建线程sub
	rv = pthread_create(&tid, &thread_attr, thread_sub, &mqtt);
	if(rv < 0)
	{
		printf("Create thread_sub failure: %s\n", strerror(errno));
		goto cleanup;
	}
	printf("Create thread_sub OK!\n");

	//创建线程pub
	rv = pthread_create(&tid, &thread_attr, thread_pub, &mqtt);
	if(rv < 0)
	{
		printf("Create thread_pub failure: %s\n", strerror(errno));
		goto cleanup;
	}
	printf("Create thread_pub OK!\n");

	while(!g_stop)
	{
		sleep(1);
	}

cleanup:
	database_term(mqtt.db);
	pthread_attr_destroy(&thread_attr);
	mosquitto_lib_cleanup();

	return 0;
} 

void signal_handler(int signum)
{
	if(SIGTERM == signum)
	{
		printf("SIGTERM is detected\n");
		g_stop = 1;
	}
}

void print_usage(char *progname)
{
	printf("%s usage:\n", progname);
	printf("-P(--platform): sepcify platform choice\n");
	printf("-t(--time): sepcify time\n");
	printf("-d(--daemon): sepcify daemon run\n");
	printf("-h(--help): print this help information\n");

	return;
}
